package org.example.platform.config;

import org.example.platform.genter.SMSCodeTokenGranter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableAuthorizationServer // 开启授权服务器
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 该对象用于刷新token提供支持
     */
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * diaoyongredis的，将令牌缓存到redis中，以便微服务之间获取信息
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    /**
     * 第三步
     * 支持client——id和client——secret做登录认证
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }

    /**
     * 第一步
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // 认证模式：password模式
                .withClient("password")
                // 授权模式
                .authorizedGrantTypes("password","refresh_token")
                // token的过期时间
                .accessTokenValiditySeconds(1800)
                // 资源id
                .resourceIds("rids")
                .scopes("all")
                .and()
                .withClient("phone")
                .secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("refresh_token","authorization_code","sms_code")
                .accessTokenValiditySeconds(3600)
                .scopes("uii")
                // secret密码
                .secret(passwordEncoder().encode("123456"));
    }

    /**

     *  * 第二步
     *      * 令牌的存储，用于支持password模式以及令牌刷新
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
       endpoints
               // 配置令牌的存储
               .tokenStore(new RedisTokenStore(redisConnectionFactory))
               .tokenGranter(tokenGranter(endpoints)) // 增加短信验证类型
               .authenticationManager(authenticationManager)
               .userDetailsService(userDetailsService);
    }


    public TokenGranter tokenGranter(AuthorizationServerEndpointsConfigurer endpoints){
        List<TokenGranter> granterList = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
        // 构建短信验证授权类型
        SMSCodeTokenGranter smsCodeTokenGranter = new SMSCodeTokenGranter(endpoints.getTokenServices(),endpoints.getClientDetailsService(),endpoints.getOAuth2RequestFactory());
        // 向短信TokenGranter传递账号 用于查询手机号关联的用户细腻系
        // 加密对象也得传过去
        smsCodeTokenGranter.setPasswordEncoder(passwordEncoder);
                // 向集合添加短信授权模型
        granterList.add(smsCodeTokenGranter);
        // 返回所有类型
        return new CompositeTokenGranter(granterList);
    }
}
